var DBFactory = require('../db/mysql');
var async = require('async');
var postHelper = require('./../util/postHelper');
var CONFIG = require('./../config');
var usersDao = module.exports;

usersDao.regist = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.getConnection(function (error, connection) { //使用transaction进行转账
            if (error) {
                cb(error);
            } else {
                async.waterfall([
                    function (callback) {
                        connection.beginTransaction(function (err) {
                            callback(err);
                        });
                    },
                    //验证account
                    function (callback) {
                        var sql = 'select * from users where account = ? and app_sid = ?';
                        connection.query(sql, [data.account, data.app_sid], function (err, result) {
                            if (err) {
                                cb(null, {
                                    status: 201,
                                    msg: '查找用户失败！'
                                });
                            } else {
                                var userInfo = result && result.length > 0 ? result[0] : null;

                                if (userInfo) {
                                    cb(null, {
                                        status: 201,
                                        msg: '用户已存在！'
                                    });
                                } else {
                                    callback(err, {
                                        status: 200
                                    });
                                }
                            }
                        });
                    },
                    function (release_info, callback) {
                        if (release_info.status != 200) { //用户已存在
                            cb(null, {
                                status: 201,
                                msg: '已经存在该用户，请直接登录！'
                            });
                        } else {
                            if (data.recommend_code) {
                                var sql = 'select count(*) as count from users where account = ? and app_sid = ? limit 1';
                                var value = [data.recommend_code, data.app_sid];
                                connection.query(sql, value, function (err, result) {
                                    if (err) {
                                        cb(null, {
                                            status: 201,
                                            msg: err
                                        });
                                    } else {
                                        if (result[0].count == 0) {
                                            cb(null, {
                                                status: 201,
                                                msg: '推荐码不存在！'
                                            });
                                        } else {
                                            callback(null, {
                                                status: 200,
                                                msg: '推荐码存在!'
                                            });
                                        }
                                    }
                                });
                            } else {
                                callback(null, {
                                    status: 200,
                                    msg: '主动注册，无需推荐码!'
                                });
                            }
                        }
                    },
                    function (release_info, callback) {
                        if (release_info.status != 200) { //邀请码不存在
                            cb(null, {
                                status: 201,
                                msg: '抱歉，邀请码不存在！'
                            });
                        } else {
                            if (data.recommend_code) {
                                var sql = 'update user_score set score = score + 15 where app_sid = ? and account = ?';
                                var value = [data.app_sid, data.recommend_code];
                                connection.query(sql, value, function (err, result) {
                                    if (err) {
                                        cb(null, {
                                            status: 201,
                                            msg: err
                                        });
                                    } else {
                                        if (result.affectedRows == 0) {
                                            cb(null, {
                                                status: 201,
                                                msg: '奖励邀请人积分出现异常！'
                                            });
                                        } else {
                                            callback(null, {
                                                status: 200,
                                                msg: '奖励邀请人积分成功!'
                                            });
                                        }
                                    }
                                });
                            } else {
                                callback(null, {
                                    status: 200,
                                    msg: '主动注册，无需赠送积分!'
                                });
                            }
                        }
                    },
                    function (release_info, callback) {
                        if (release_info.status != 200) { //赠送邀请人积分失败
                            cb(null, {
                                status: 201,
                                msg: '抱歉，奖励邀请人积分失败！'
                            });
                        } else {
                            if (data.recommend_code) {
                                var users = {
                                    account: data.recommend_code,
                                    app_sid: data.app_sid,
                                    created_date: new Date(),
                                    type: 2,
                                    score: 15,
                                    comment: '邀请用户注册赠送积分'
                                }
                                var sql = 'insert into score_info set ?';
                                connection.query(sql, users, function (err, result) {
                                    if (err) {
                                        cb(null, {
                                            status: 201,
                                            msg: '赠送注册积分error！'
                                        });
                                    } else {
                                        if (result.affectedRows == 0) {
                                            cb(null, {
                                                status: 201,
                                                msg: '赠送注册积分异常！'
                                            });
                                        } else {
                                            callback(null, {
                                                status: 200,
                                                msg: '用户注册成功!'
                                            });
                                        }
                                    }
                                });
                            } else {
                                callback(null, {
                                    status: 200,
                                    msg: '主动注册，无需赠送积分!'
                                });
                            }
                        }
                    },
                    function (release_info, callback) {
                        if (release_info.status != 200) { //邀请码不存在
                            cb(null, {
                                status: 201,
                                msg: '抱歉，邀请码不存在！'
                            });
                        } else {
                            var users = {
                                account: data.account,
                                password: data.password,
                                app_sid: data.app_sid,
                                username: data.username,
                                comment: data.comment,
                                uuid: data.uuid,
                                avatar: data.avatar,
                                created_date: new Date(),
                                status: 1
                            }

                            if (data.recommend_code) {
                                users.recommend_code = data.recommend_code;
                            }
                            var sql = 'insert into users set ?';
                            connection.query(sql, users, function (err, result) {
                                if (err) {
                                    cb(null, {
                                        status: 201,
                                        msg: err
                                    });
                                } else {
                                    if (result.affectedRows == 0) {
                                        cb(null, {
                                            status: 201,
                                            msg: '用户注册异常！'
                                        });
                                    } else {
                                        callback(null, {
                                            status: 200,
                                            msg: '用户表注册成功!'
                                        });
                                    }
                                }
                            });
                        }
                    },
                    function (release_info, callback) {
                        if (release_info.status != 200) { //用户表注册异常
                            cb(null, {
                                status: 201,
                                msg: '抱歉，用户注册失败！'
                            });
                        } else {
                            var users = {
                                account: data.account,
                                app_sid: data.app_sid,
                                created_date: new Date(),
                                status: 1,
                                score: 300,
                                uuid: data.uuid
                            }
                            var sql = 'insert into user_score set ?';
                            connection.query(sql, users, function (err, result) {
                                if (err) {
                                    cb(null, {
                                        status: 201,
                                        msg: err
                                    });
                                } else {
                                    if (result.affectedRows == 0) {
                                        cb(null, {
                                            status: 201,
                                            msg: '用户积分注册异常！'
                                        });
                                    } else {
                                        callback(null, {
                                            status: 200,
                                            msg: '用户积分表生成成功!'
                                        });
                                    }
                                }
                            });
                        }
                    },
                    function (release_info, callback) {
                        if (release_info.status != 200) { //用户表注册异常
                            cb(null, {
                                status: 201,
                                msg: '抱歉，用户积分记录生成失败！'
                            });
                        } else {
                            var users = {
                                account: data.account,
                                app_sid: data.app_sid,
                                created_date: new Date(),
                                type: 1,
                                score: 300,
                                comment: '用户注册赠送积分'
                            }
                            var sql = 'insert into score_info set ?';
                            connection.query(sql, users, function (err, result) {
                                if (err) {
                                    cb(null, {
                                        status: 201,
                                        msg: '赠送注册积分error！'
                                    });
                                } else {
                                    if (result.affectedRows == 0) {
                                        cb(null, {
                                            status: 201,
                                            msg: '赠送注册积分异常！'
                                        });
                                    } else {
                                        callback(null, true, {
                                            status: 200,
                                            msg: '用户注册成功!'
                                        });
                                    }
                                }
                            });
                        }
                    }
                ], function (DbErr, isSuccess, uidOrInfo) {
                    if (DbErr) {
                        connection.rollback(function () {
                            connection.release();
                            cb(DbErr);
                        });
                    } else if (!isSuccess) {
                        connection.rollback(function () {
                            connection.release();
                            cb(DbErr);
                        });
                    } else {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, uidOrInfo);
                            }
                        });
                    }
                });
            }
        });
    }
}

usersDao.login = function (data, cb) {
    var sql = 'select * from users where account = ? and app_sid = ?';
    var value = [data.account, data.app_sid];

    DBFactory.executeSql(sql, value, 'usersDao.login', autoCbErrFunction(cb, function (result) {
        var del_info = result && result.length > 0 ? result[0] : null;

        if (!del_info) {
            cb(null, {
                status: 201,
                msg: '未找到用户记录!'
            });
        } else {
            if (del_info.password == data.password) {
                cb(null, {
                    status: 200,
                    userInfo: del_info
                });
            } else {
                cb(null, {
                    status: 201,
                    msg: '账号或密码不正确!'
                });
            }
        }
    }));
}

usersDao.get_user_score = function (data, cb) {
    var sql = 'select * from user_score where account = ? and app_sid = ?';
    var value = [data.account, data.app_sid];

    DBFactory.executeSql(sql, value, 'usersDao.get_user_score', autoCbErrFunction(cb, function (result) {
        var del_info = result && result.length > 0 ? result[0] : null;

        if (!del_info) {
            cb(null, {
                status: 201,
                msg: '未找到用户积分记录!'
            });
        } else {
            cb(null, {
                status: 200,
                userInfo: del_info
            });
        }
    }));
}

usersDao.verifyCode = function (data, cb) {
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            return cb(error);
        }

        async.waterfall([
            function (callback) {
                connection.beginTransaction(function (err) {
                    return callback(err);
                });
            },
            //验证验证码
            function (callback) {
                var sql = 'select * from verify_codes where phone = ? and app_sid = ? and type = ?';
                var value = [data.account, data.app_sid, data.type];
                connection.query(sql, value, function (err, result) {
                    if (err) {
                        return callback(err);
                    }

                    var user_info = result && result.length > 0 ? result[0] : null;

                    if (!user_info) {
                        return callback('未查询到验证码！');
                    }

                    if (new Date().getTime() - new Date(user_info.create_time).getTime() > 1000 * 60 * 30) {
                        return callback('验证码已过期！');
                    } 

                    if (data.verify_code == user_info.verify_code) {
                        return callback(null, {
                            status: 200,
                            userInfo: user_info
                        });
                    } 
                    
                    if (user_info.err_num == 5) {
                        return callback(null, {
                            status: 202,
                            userInfo: user_info
                        });
                    } 
                    
                    return callback(null, {
                        status: 203,
                        userInfo: user_info
                    });
                });
            },
            function (release_info, callback) {
                if (release_info.status == 202) {
                    var sql = 'delete from verify_codes where phone = ? and app_sid = ?';
                    var value = [data.account, data.app_sid];
                    connection.query(sql, value, function (err, result) {
                        if (err) {
                            return callback(err);
                        } 
                        
                        if (result.affectedRows == 0) {
                            return callback('删除验证码异常！');
                        } 
                        
                        return callback('验证码输入次数超过5次，请重新获取！');
                    });
                } else if (release_info.status == 203) {
                    var sql = 'update verify_codes set err_num = err_num + 1 where phone = ? and type = ? and app_sid = ?';
                    var value = [data.account, data.type, data.app_sid];

                    connection.query(sql, value, function (err, result) {
                        if (err) {
                            return callback(err);
                        } 
                        
                        if (result.affectedRows == 0) {
                            return callback('更新验证码错误次数异常！');
                        } 
                        
                        return callback('验证码输入错误' + (release_info.userInfo.err_num + 1) + '次!');
                    });
                } else if (release_info.status == 200) {
                    var sql = 'delete from verify_codes where phone = ? and app_sid = ?';
                    var value = [data.account, data.app_sid];
                    connection.query(sql, value, function (err, result) {
                        if (err) {
                            return callback(err);
                        } 
                        
                        if (result.affectedRows == 0) {
                            return callback('找不到要删除的验证码！');
                        } 
                        
                        return callback(null, true, {
                            status: 200,
                            msg: '验证成功删除验证码成功!'
                        });
                    });
                }
            }
        ], function (DbErr, isSuccess, uidOrInfo) {
            if (DbErr || !isSuccess) {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                        });
    
                        return cb(e);
                    }
    
                    connection.release();
                    return cb(DbErr);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                        });
    
                        return cb(e);
                    }
    
                    connection.release();
                    return cb(null, uidOrInfo);
                });
            }
        });
    });
}

usersDao.saveVerifyCode = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.getConnection(function (error, connection) { //使用transaction进行转账
            if (error) {
                cb(error);
            } else {
                async.waterfall([
                    // 开始Transaction
                    function (callback) {
                        connection.beginTransaction(function (err) {
                            callback(err);
                        });
                    },
                    //验证验证码
                    function (callback) {
                        var sql = 'delete from verify_codes where phone = ? and app_sid = ? and type = ?';
                        var value = [data.account, data.app_sid, data.type];
                        connection.query(sql, value, function (err, result) {
                            if (err) {
                                cb({
                                    status: 201,
                                    msg: err
                                });
                            } else {
                                callback(null, {
                                    status: 200,
                                    msg: '删除验证码成功!'
                                });
                            }
                        });
                    },
                    function (release_info, callback) {
                        var sql = 'insert into verify_codes set ?';
                        var value = {
                            phone: data.account,
                            verify_code: data.code,
                            create_time: new Date(),
                            create_num: 0,
                            err_num: 0,
                            type: data.type,
                            ip: '127.0.0.1',
                            app_sid: data.app_sid
                        };
                        connection.query(sql, value, function (err, result) {
                            if (err) {
                                cb(null, {
                                    status: 201,
                                    msg: err
                                });
                            } else {
                                if (result.affectedRows == 0) {
                                    cb(null, {
                                        status: 201,
                                        msg: '获取验证码出现异常！'
                                    });
                                } else {
                                    callback(err, true, {
                                        status: 200,
                                        msg: '获取验证码成功!'
                                    });
                                }
                            }
                        });
                    }
                ], function (DbErr, isSuccess, uidOrInfo) {
                    if (DbErr) {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, DbErr);
                            }
                        });
                    } else if (!isSuccess) {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, DbErr);
                            }
                        });
                    } else {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, uidOrInfo);
                            }
                        });
                    }
                });
            }
        });
    }
}

usersDao.getOpenidInfo = function (data, cb) {
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            return cb(error);
        }

        async.waterfall([
            function (callback) {
                connection.beginTransaction(function (err) {
                    return callback(err);
                });
            },
            function (callback) {
                postHelper.baseRequest('https://api.weixin.qq.com/sns/jscode2session', {
                    appid: 'wxf1e46ee836faaea8',
                    secret: '40a3afb072990d20ad6e98153402889a',
                    js_code: data.code,
                    grant_type: 'authorization_code'
                }, function (err, result) {
                    if (err) {
                        return callback(err);
                    }

                    return callback(null, JSON.parse(result));
                });
            },
            function (info, callback) {
                var sql = 'select * from users where openid = ?';
                var value = [info.openid];
                connection.query(sql, value, function (err, result) {
                    if (err) {
                        return callback(err);
                    }

                    var user_info = result && result.length > 0 ? result[0] : null;

                    if (!user_info) {
                        return callback(null, true, info.openid);
                    }

                    return callback(user_info);
                });
            }
        ], function (DbErr, isSuccess, uidOrInfo) {
            if (DbErr || !isSuccess) {
                connection.rollback(function () {
                    connection.release();
                });

                return cb(DbErr);
            }

            connection.commit(function (e) {
                if (e) {
                    connection.rollback(function () {
                        connection.release();
                    });

                    return cb(e);
                }

                connection.release();
                return cb(null, uidOrInfo);
            });
        });
    });
}

usersDao.wx_regist = function (data, cb) {
    DBFactory.getConnection(function (error, connection) { //使用transaction进行转账
        if (error) {
            return cb(error);
        }

        async.waterfall([
            function (callback) {
                connection.beginTransaction(function (err) {
                    return callback(err);
                });
            },
            //验证account
            function (callback) {
                var sql = 'select * from users where account = ? and app_sid = ?';
                connection.query(sql, [data.account, data.app_sid], function (err, result) {
                    if (err) {
                        return callback(err);
                    }

                    var userInfo = result && result.length > 0 ? result[0] : null;

                    if (userInfo) {
                        return callback('手机号已绑定其他用户,请先解绑!');
                    }

                    return callback(err, 200);
                });
            },
            function (release_info, callback) {
                var users = {
                    account: data.account,
                    password: data.password,
                    app_sid: data.app_sid,
                    username: data.nickName,
                    uuid: data.uuid,
                    avatar: data.avatarUrl,
                    city: data.city,
                    gender: data.gender,
                    openid: data.openid,
                    province: data.province,
                    created_date: new Date(),
                    status: 1
                }

                var sql = 'insert into users set ?';
                connection.query(sql, users, function (err, result) {
                    if (err) {
                        return callback(err);
                    }

                    if (result.affectedRows == 0) {
                        return callback('注册出现异常!')
                    }

                    return callback(null, '用户表注册成功!');
                });
            },
            function (release_info, callback) {
                var users = {
                    account: data.account,
                    app_sid: data.app_sid,
                    created_date: new Date(),
                    status: 1,
                    score: 300,
                    uuid: data.uuid
                }
                var sql = 'insert into user_score set ?';
                connection.query(sql, users, function (err, result) {
                    if (err) {
                        return callback(err);
                    }

                    if (result.affectedRows == 0) {
                        return callback('用户积分记录生成异常！')
                    }

                    return callback(null, '用户积分记录生成成功!');
                });
            },
            function (release_info, callback) {
                var users = {
                    account: data.account,
                    app_sid: data.app_sid,
                    created_date: new Date(),
                    type: 1,
                    score: 300,
                    comment: '用户注册赠送积分'
                }
                var sql = 'insert into score_info set ?';
                connection.query(sql, users, function (err, result) {
                    if (err) {
                        return callback(err);
                    }

                    if (result.affectedRows == 0) {
                        return callback('用户积分数据异常！')
                    }

                    return callback(null, true, '用户积分表生成成功!');
                });
            }
        ], function (DbErr, isSuccess, uidOrInfo) {
            if (DbErr || !isSuccess) {
                connection.rollback(function () {
                    connection.release();
                });

                return cb(DbErr);
            }

            connection.commit(function (e) {
                if (e) {
                    connection.rollback(function () {
                        connection.release();
                    });

                    return cb(e);
                }

                connection.release();
                return cb(null, uidOrInfo);
            });
        });
    });
}

usersDao.user_defined = function (data, cb) {
    DBFactory.getConnection(function (error, connection) { //使用transaction进行转账
        if (error) {
            return cb(error);
        }

        async.waterfall([
            function (callback) {
                connection.beginTransaction(function (err) {
                    return callback(err);
                });
            },
            //获取access_token
            function (callback) {
                postHelper.baseRequest(CONFIG.USERDEFINEPATH, {
                    grant_type: CONFIG.USERDEFINEGRANTTYPE,
                    client_id: CONFIG.USERDEFINEKEY,
                    client_secret: CONFIG.USERDEFINESECRET
                }, function(err, result) {
                    if(err) {
                        return callback(err);
                    }

                    return callback(null, JSON.parse(result).access_token);
                });
            },

            //图像审核
            function (access_token, callback) {
                postHelper.baseRequestbdai(CONFIG.CENSORINGPATH + access_token, {
                    imgUrl: data,
                    imgType: CONFIG.CENSORINGIMGTYPE
                }, function(err, result) {
                    if(err) {
                        return callback(err);
                    }

                    if(result.error_code) {
                        return callback(result.error_msg);
                    }

                    if(result.conclusionType != 1) {
                        return callback('图片内容不合法，请重新上传吧!');
                    }

                    return callback(null, true, result);
                });
            }
        ], function (DbErr, isSuccess, uidOrInfo) {
            if (DbErr || !isSuccess) {
                connection.rollback(function () {
                    connection.release();
                });

                return cb(DbErr);
            }

            connection.commit(function (e) {
                if (e) {
                    connection.rollback(function () {
                        connection.release();
                    });

                    return cb(e);
                }

                connection.release();
                return cb(null, uidOrInfo);
            });
        });
    });
}

usersDao.text_define = function (data, cb) {
    DBFactory.getConnection(function (error, connection) { //使用transaction进行转账
        if (error) {
            return cb(error);
        }

        async.waterfall([
            function (callback) {
                connection.beginTransaction(function (err) {
                    return callback(err);
                });
            },
            //获取access_token
            function (callback) {
                postHelper.baseRequest(CONFIG.USERDEFINEPATH, {
                    grant_type: CONFIG.USERDEFINEGRANTTYPE,
                    client_id: CONFIG.USERDEFINEKEY,
                    client_secret: CONFIG.USERDEFINESECRET
                }, function(err, result) {
                    if(err) {
                        return callback(err);
                    }

                    return callback(null, JSON.parse(result).access_token);
                });
            },

            //文本审核
            function (access_token, callback) {
                postHelper.baseRequestbdai(CONFIG.CENSORINGTEXTPATH + access_token, {
                    text: data.text
                }, function(err, result) {
                    if(err) {
                        return callback(err);
                    }

                    if(result.error_code) {

                        return callback(result.error_msg);
                    }

                    if(result.conclusionType != 1) {
                        return callback('文本内容不合法，请重新上传吧!');
                    }

                    return callback(null, true, result);
                });
            }
        ], function (DbErr, isSuccess, uidOrInfo) {
            if (DbErr || !isSuccess) {
                connection.rollback(function () {
                    connection.release();
                });

                return cb(DbErr);
            }

            connection.commit(function (e) {
                if (e) {
                    connection.rollback(function () {
                        connection.release();
                    });

                    return cb(e);
                }

                connection.release();
                return cb(null, uidOrInfo);
            });
        });
    });
}